package com.fanshuai.queue.blocking;

import com.fanshuai.queue.Queue;

public class LinkedBlockingQueue<E> implements Queue<E> {
    public static class Node<E> {
        public E data;
        public Node<E> pre;
        public Node<E> next;

        public Node(E data) {
            this.data = data;
            this.pre = null;
            this.next = null;
        }

        public Node() {
            this.data = null;
            this.pre = null;
            this.next = null;
        }
    }

    private Node<E> head;
    private Node<E> tail;
    private int size;

    /**
     * 数据锁
     */
    private final Object dataLock = new Object();

    /**
     * 队列空锁
     */
    private final Object emptyLock = new Object();

    public LinkedBlockingQueue() {
        Node<E> node = new Node<>();
        head = node;
        tail = node;
        size = 0;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return false;
    }

    @Override
    public void enqueue(E data) {
        Node<E> node = new Node<>(data);
        synchronized (dataLock) {
            tail.next = node;
            node.pre = tail;

            tail = node;
            size++;
        }

        synchronized (emptyLock) {
            emptyLock.notifyAll();
        }
    }

    @Override
    public E dequeue() {
        while (isEmpty()) {
            synchronized (emptyLock) {
                try {
                    emptyLock.wait();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        E data = null;
        synchronized (dataLock) {
            Node<E> node = head.next;
            head.next = node.next;
            if (node.next != null) {
                node.next.pre = head;
            }

            data = node.data;
            if (node.next == null) {
                tail = node.pre;
            }

            node.next = null;
            node.pre = null;
            node.data = null;

            size--;
        }
        return data;
    }

    @Override
    public E peek() {
        Node<E> node = head.next;
        return null == node ? null : node.data;
    }
}
